<template>
  <div class="pl-2 pr-2">
    <Card
      style="margin-bottom: 5px"
      :bodyStyle="{ padding: '5px', overflow: 'auto', minHeight: '80px' }"
    >
      <template #title>
        <div>{{ title }}<text style="color: red">*</text> </div>
      </template>
      <template #extra>
        <a-button type="primary" @click="handleAdd" v-if="list.length != nameList.length"
          >添加字段</a-button
        >
      </template>
      <draggable
        v-model="list"
        :component-data="{
          type: 'transition-group',
        }"
        :animation="180"
        handle=".draggable-item"
      >
        <template #item="{ element, index }">
          <div
            class="flex items-center justify-between mb-1 p-2"
            :style="[{ borderBottom: list.length - 1 != index ? '1px solid #efefef' : '' }]"
          >
            <div class="text-center ellipsis" style="width: 30%" :type="element.title">
              <Select
                :options="element.nameList"
                v-model:value="element.name"
                placeholder="请选择"
                style="width: 97%"
                showSearch
                optionFilterProp="label"
                :field-names="{ label: 'label', value: 'label' }"
                allow-clear
                @change="handleChangeParam($event, index)"
              />
            </div>
            <div class="text-center flex items-center" style="width: 30%">
              <div class="text-center w-full"> 的值赋予 </div></div
            >
            <div class="text-center" style="width: 30%">
              <Select
                :options="formGetFieldsData"
                v-model:value="element.value"
                placeholder="请选择"
                style="width: 98%; text-align: left"
                showSearch
                optionFilterProp="title"
                :field-names="{ label: 'title', value: 'name' }"
                allow-clear
              />
            </div>
            <div class="text-center flex justify-center" style="width: 100px">
              <DeleteOutlined
                class="cursor-pointer mr-2"
                style="color: red"
                title="删除"
                @click="handleDelete({ index })"
              />
            </div>
          </div>
        </template>
      </draggable>
    </Card>
  </div>
  <ExprModal @register="registerExprModal" @success="handleExprModalSuccess" />
</template>
<script lang="ts" setup>
  import { ref, watch, nextTick } from 'vue';
  import { Card, Select, Input } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import draggable from 'vuedraggable';
  import { DeleteOutlined } from '@ant-design/icons-vue';
  import { useModal } from '/@/components/Modal';
  import { ExprModal } from '/@/components/CustomComp';
  import { getFormGetFields, getFormGetNestFieldsWithFormName } from '/@/api/flowManage/flowManage';
  const { createMessage } = useMessage();
  const props = defineProps({
    formCode: {
      type: String as PropType<string>,
      default: '',
    },
    typeCode: {
      type: String as PropType<string>,
      default: '',
    },
    modelValue: {
      type: Array,
      default: () => [],
    },
    title: {
      type: String as PropType<string>,
      default: '',
    },
    nameList: {
      type: Array,
      default: () => [],
    },
  });
  const emit = defineEmits(['update:modelValue']);
  const updateModelValue = () => {
    emit('update:modelValue', list.value);
  };
  const list: any = ref([]);
  const index = ref(-1);
  const nameList = ref<any[]>([]); //总的参数数组

  const fetch = async () => {
    await nextTick();
    list.value = props.modelValue || [];
  };
  watch(
    () => props.modelValue,
    async () => {
      fetch();
    },
    {
      immediate: true,
    },
  );
  watch(
    () => props.formCode,
    async () => {
      await nextTick();
      getFormGetFieldsData();
    },
    {
      immediate: true,
    },
  );

  watch(
    () => props.nameList,
    async () => {
      await nextTick();
      nameList.value = props.nameList || [];
      console.log('watch nameList', nameList.value);
    },
    {
      immediate: true,
    },
  );
  watch(
    () => list.value,
    async () => {
      updateModelValue();
    },
  );
  const [registerExprModal, { openModal }] = useModal();
  //新增
  const handleAdd = () => {
    index.value = -1;
    list.value.push({
      nameList: [],
      type: 'value',
      name: '',
      value: '',
    });
    calcParam();
  };
  //删除
  const handleDelete = ({ index }) => {
    list.value.splice(index, 1);
    calcParam();
  };
  defineExpose({
    list,
  });

  //获取表单字段
  const formGetFieldsData = ref<any>([]);
  const getFormGetFieldsData = async () => {
    if (!props.formCode) return;
    await getFormGetFields({ formCode: props.formCode }).then((res) => {
      formGetFieldsData.value = res || [];
      formGetFieldsData.value.forEach((item: any) => {
        delete item.options;
      });
    });

    let params = {
      formCode: props.formCode,
    };
    await getFormGetNestFieldsWithFormName(params).then((res) => {
      let data = res || [];
      data.forEach((item) => {
        delete item.options;
        item.name = `${item.nestFieldName}.${item.formCode}.${item.name}`;
        item.title = `${item.formName}-${item.title}`;
      });
      formGetFieldsData.value = [...formGetFieldsData.value, ...data];
    });
  };

  const handleExprModalSuccess = (val) => {
    list.value[index.value].value = val;
  };

  //改变条件
  const handleChangeParam = (value, index) => {
    if (value) {
      const record = nameList.value.find((item) => item.name == value);
      if (record) {
        list.value[index].value = record.value;
      }
    }
    calcParam();
  };
  //计算选择的参数值
  const calcParam = () => {
    const params = list.value.filter((item) => item.name).map((el) => el.name);
    const newParamList = nameList.value.filter((item) => !params.includes(item.name));
    list.value.forEach((item) => {
      if (item.name) {
        item.nameList = nameList.value.filter((el) => el.name == item.name);
      } else {
        item.nameList = newParamList;
      }
    });
  };
</script>
<style scoped>
  .ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
</style>
